package com.tanhua.dubbo.api.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void updateOrSaveLocation(Long userId, Double latitude, Double longitude, String addrStr) {
        //1.先查询用户是否存在位置
        Query query = new Query(Criteria.where("userId").is(userId));
        boolean exists = mongoTemplate.exists(query, UserLocation.class);

        if (exists) {
            //2.如果存在，则更新location
            UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
            Update update = new Update();
            update.set("location", new GeoJsonPoint(longitude, latitude));
            update.set("address", addrStr);
            update.set("updated", System.currentTimeMillis());
            update.set("lastUpdated", location.getUpdated());
            mongoTemplate.updateFirst(query, update, UserLocation.class);

        } else {
            //3.如果不存在，则新建一个location
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude, longitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }

    }

    @Override
    public List<Long> searchNearUser(Long userId, Integer distance) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        Distance distance1 = null;
        if (distance != 0) {
            distance1 = new Distance(distance / 1000, Metrics.KILOMETERS);
        }
        Circle circle = new Circle(userLocation.getLocation(),distance1);
        Query query1 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);
        List<Long> nearUserIds = CollUtil.getFieldValues(userLocations, "userId", Long.class);
        return nearUserIds;
    }
}
